﻿using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace SiriRobot
{
    public partial class FrmSysConfig : Form
    {
        public FrmSysConfig()
        {
            InitializeComponent();
            InitializeConfig();
        }

        private void InitializeConfig()
        {
            var config = EasyConf.Read<Config>();

            txtClientId.Text = config.ClientId;
            txtMQTTPort.Text = config.MQTTPort.ToString();
            txtMQTTServer.Text = config.MQTTServer;
            txtUserName.Text = config.UserName;
            txtPassword.Text = config.Password;
            txtUrl.Text = config.Url;
            cbAutoStart.Checked = config.AutoRun;
        }

        private void CloseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void SaveCloseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveConfig();
            this.Close();
        }

        private void SaveRestartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveConfig();

            //Application.Restart();

            Process.Start(Application.ExecutablePath);
            Process.GetCurrentProcess().Kill();
        }

        private void SaveConfig()
        {
            var config = EasyConf.Read<Config>();

            config.MQTTServer = txtMQTTServer.Text.Trim();
            config.UserName = txtUserName.Text.Trim();
            config.Password = txtPassword.Text.Trim();
            config.Url = txtUrl.Text.Trim();
            config.AutoRun = cbAutoStart.Checked;

            if (uint.TryParse(txtMQTTPort.Text.Trim(), out uint port))
            {
                config.MQTTPort = (int)port;
            }
            else
            {
                MessageBox.Show($"端口设置错误,一般为:1883 这种数字格式");
                return;
            }
            EasyConf.Write(config);

            RegistryHelper.AutoRun(cbAutoStart.Checked);
        }
    }
}
